/*
Copyright © 2022 NAME HERE <EMAIL ADDRESS>

*/
package cmd

import (
	"gitee.com/bjf-fhe/apicat/errors"
	"gitee.com/bjf-fhe/apicat/openapi"
	"github.com/getkin/kin-openapi/openapi3"
	"github.com/sirupsen/logrus"
	"github.com/spf13/cobra"
)

// mergeCmd represents the merge command
var mergeCmd = &cobra.Command{
	Use:   "merge",
	Short: "用于将界面操作中的OpenAPI增量文件进行合并",
	Long:  `合并两个OpenAPI定义，并生成合并后的文件`,
	Run: func(cmd *cobra.Command, args []string) {
		dest, _ := cmd.Flags().GetString("dest")
		logrus.Infoln("开始执行Apicat定义合并程序")
		//load orginial
		api, _, err := rootConfig.LoadApi(false)
		if err == nil {
			if len(args) == 0 {
				err = errors.New(errors.NoToMergeFile)
			} else {
				//load merged
				var toMergeDef *openapi3.T
				toMergeDef, err = openapi.LoadFile(args[0])
				if err == nil {
					var merged = openapi.Merge(api, toMergeDef)
					err = openapi.Save(merged, dest)
				}
			}
		}
		if err != nil {
			logrus.Fatal(err)
		} else {
			logrus.Errorln("合并成功！")
		}
	},
}

func init() {
	rootCmd.AddCommand(mergeCmd)

	mergeCmd.Flags().String("dest", "./openapi.merged.yaml", "输出文件名")

}
